import 'dart:async';
import 'dart:convert';

import 'package:date_format/date_format.dart';
import 'package:dio/dio.dart';
import 'package:ditieapp/page/json/datalog.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../json/message.dart';
import '../provider/LoginProvider.dart';

class SpeedBoatPage extends StatefulWidget {
  @override
  _SpeedBoatPageState createState() => _SpeedBoatPageState();
}

class _SpeedBoatPageState extends State<SpeedBoatPage> {

  var url = "http://175.178.187.21:18000";  //本地环境 https://188l877k45.zicp.vip  //生产环境 http://175.178.187.21:18000
  //var produce = url+"";   //生产环境

  List<Message?> message = [];

  List<Datalog?> dataLog = [];

  //Map address = {};

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getAddress();
    int _count = 0;
    Timer.periodic(const Duration(seconds: 5), (timer) {
      _count++;
      //print('count: $_count');
      if (_count == 30) {

        //清除定时器
        timer.cancel();
        _count = 0;
      }

      //获取当前是否已连接
      getMessage();

      //获取当前连接的数据以及操作指令
      getLogData();
    });
  }

  //获取经纬度
  void getAddress()async{

    var result =
        await new Dio().post(url+"/iot/amap/find");

    if(result.data != null){


      context.read<LoginProvider>().setlongitude(result.data["longitude"].toString());  //经度
      context.read<LoginProvider>().setLatitude(result.data["latitude"].toString());    //纬度
      context.read<LoginProvider>().setaddressTime(result.data["createTime"].toString());    //定位时间

    }



  }

  //获取连接信息
  void getMessage() async {
    var result =
        await new Dio().post(url+"/iot/data/desc");
    var time = result.data[0]["createTime"];
    DateTime nettime = DateTime.parse(time);
    //print(formatDate(nettime,[nettime.year,'年',nettime.month,'月',nettime.day]));
    //print(formatDate(DateTime.parse(time), [DateTime.parse(time).year.toString(),'年',DateTime.parse(time).month.toString(),'月',DateTime.parse(time).day.toString()+"日",' ',DateTime.parse(time).hour.toString(),':',DateTime.parse(time).minute.toString()]));

    // print(formatDate(_nowDate,[yyyy,'年',mm,'月',dd,' ',HH,':',nn]))
    List<Message?> list = (result.data as List<dynamic>)
        .map((e) => Message.fromMap((e as Map<String, dynamic>)))
        .toList();

    setState(() {
      message = list;
    });
  }

  //获取操作指令日志
  void getLogData() async {
    var result =
        await new Dio().post(url+"/iot/log/data/1/10");
    var time = result.data["records"][0]["create_time"];
    var data1 = result.data["records"][0]["iot_data"];
    DateTime nettime = DateTime.parse(time);
    var timesss = formatDate(nettime, [
      nettime.year.toString(),
      '-',
      nettime.month.toString(),
      '-',
      nettime.day.toString(),
      ' ',
      HH,
      ':',
      nn
    ]);
    print(1);

    List<Datalog?> list = (result.data["records"] as List<dynamic>)
        .map((e) => Datalog.fromMap((e as Map<String, dynamic>)))
        .toList();
    setState(() {
      dataLog = list;
    });
  }

  void getstart() async {
    var result =
        await new Dio().post(url+"/emqxPublish/2");
    print(result);
  }

  void bottom() async {
    var result =
        await new Dio().post(url+"/emqxPublish/3");
    print(result);
  }

  void left() async {
    var result =
        await new Dio().post(url+"/emqxPublish/4");
    print(result);
  }

  void right() async {
    var result =
        await new Dio().post(url+"/emqxPublish/5");
    print(result);
  }

  void centerstop() async {
    var result =
        await new Dio().post(url+"/emqxPublish/6");
    print(result);
  }

  void leftbottom() async {
    var result =
        await new Dio().post(url+"/emqxPublish/7");
    print(result);
  }

  void rightbottom() async {
    var result =
        await new Dio().post(url+"/emqxPublish/8");
    print(result);
  }

  void leftSheep() async {
    var result =
    await new Dio().post(url+"/emqxPublish/12");
    print(result);
  }

  void rightSheep() async {
    var result =
    await new Dio().post(url+"/emqxPublish/13");
    print(result);
  }

  void choushui() async {
    var result =
    await new Dio().post(url+"/emqxPublish/15");
    print(result);
  }

  void clearSystem() async {
    var result =
    await new Dio().post(url+"/emqxPublish/14");
    print(result);
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    message.clear();
    dataLog.clear();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("快艇控制"),
        centerTitle: true,
      ),
      body: Container(
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        //alignment: Alignment.center,
        color: Colors.amberAccent,
        child: Padding(
          padding: EdgeInsets.only(top: 20),
          child: Stack(
            alignment: Alignment.topCenter,
            children: [
              Positioned(
                child: InkWell(
                  onTap: () {
                    print("打印前进");

                    getstart();
                  },
                  child: Container(
                    alignment: Alignment.center,
                    width: 80,
                    height: 80,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(80),
                      color: Colors.blue,
                    ),
                    child: Center(
                      child: Text(
                        "前进",
                        style: TextStyle(
                            fontSize: 18,
                            color: Colors.amberAccent,
                            fontWeight: FontWeight.w800),
                      ),
                    ),
                  ),
                ),
              ),
              Positioned(
                  bottom: 15,
                  child: Padding(
                    padding: EdgeInsets.all(10),
                    child: Container(
                      width: 135,
                      height: 100,
                      decoration: BoxDecoration(color: Colors.blue,borderRadius: BorderRadius.circular(5)),
                      child: ListView(
                        children: dataLog
                            .map(
                              (e) => Padding(
                                padding: EdgeInsets.all(3),
                                child: Row(mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Text(
                                      "" +
                                          formatDate(
                                            DateTime.parse(e!.createTime.toString()),
                                            [
                                              DateTime.parse(e.createTime.toString())
                                                  .month
                                                  .toString(),
                                              '月',
                                              DateTime.parse(e.createTime.toString())
                                                  .day
                                                  .toString() +
                                                  "日",
                                              ' ',
                                              HH,
                                              ':',
                                              nn
                                            ],
                                          )
                                          //+"  --"+e.iotData

                                    ,style: TextStyle(fontSize: 12),),
                                  Text("--",style: TextStyle(fontSize: 12),),
                                  Text(""+e.iotData == "2" ? "前进":e.iotData == "3" ? "后退":e.iotData == "4" ?"左转":e.iotData == "5" ?"右转":e.iotData == "6" ? "停止":e.iotData == "7"?"加速":"减速",style: TextStyle(fontSize: 12),)
                                ],),
                              ),
                            )
                            .toList(),
                      ),
                    ),
                  )),
              Positioned(
                  left: 0,
                  child: Container(
                    width: 130,
                    height: 100,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(color: Colors.blue,borderRadius: BorderRadius.circular(5)),
                    child: Padding(
                      padding: EdgeInsets.only(left: 3,top: 5,bottom: 5),
                      child: ListView(
                        children: message
                            .map(
                              (e) => Text(
                              "" +
                                  formatDate(
                                    DateTime.parse(e!.createTime.toString()),
                                    [
                                      DateTime.parse(e.createTime.toString())
                                          .month
                                          .toString(),
                                      '月',
                                      DateTime.parse(e.createTime.toString())
                                          .day
                                          .toString() +
                                          "日",
                                      ' ',
                                      HH,
                                      ':',
                                      nn
                                    ],
                                  )+" -成功"
                            //+"--"+e.iotData == 2 ? "前进":e.iotData == 3 ? "后退":e.iotData == 4 ?"左转":e.iotData == 5 ?"右转":e.iotData == 6?"停止":e.iotData == 7?"加速":"减速"
                          ,style: TextStyle(fontSize: 12)),
                        )
                            .toList(),
                      ),
                    ),
                  )),
              Positioned(
                bottom: 100,
                left: 30,
                child: InkWell(
                  onTap: () {
                    print("houtui ");
                    //bottom();
                    //leftSheep();
                    Navigator.of(context).pushNamed("camare");
                  },
                  child: Container(
                    alignment: Alignment.center,
                    width: 60,
                    height: 40,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(40),
                      color: Colors.blue,
                    ),
                    child: Center(
                      child: Text(
                        "图传调试",
                        style: TextStyle(
                            fontSize: 14,
                            color: Colors.amberAccent,
                            fontWeight: FontWeight.w800),
                      ),
                    ),
                  ),
                ),
              ),
              Positioned(
                bottom: 100,
                right: 30,
                child: InkWell(
                  onTap: () {
                    print("houtui ");
                    //bottom();
                    Navigator.of(context).pushNamed("addmap");  // addmap  amap
                  },
                  child: Container(
                    alignment: Alignment.center,
                    width: 60,
                    height: 40,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(40),
                      color: Colors.blue,
                    ),
                    child: Center(
                      child: Text(
                        "地图",
                        style: TextStyle(
                            fontSize: 14,
                            color: Colors.amberAccent,
                            fontWeight: FontWeight.w800),
                      ),
                    ),
                  ),
                ),
              ),

              Positioned(
                bottom: 30,
                left: 30,
                child: InkWell(
                  onTap: () {
                    print("houtui ");
                    //bottom();
                    choushui();
                  },
                  child: Container(
                    alignment: Alignment.center,
                    width: 60,
                    height: 40,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(40),
                      color: Colors.blue,
                    ),
                    child: Center(
                      child: Text(
                        "抽水",
                        style: TextStyle(
                            fontSize: 14,
                            color: Colors.amberAccent,
                            fontWeight: FontWeight.w800),
                      ),
                    ),
                  ),
                ),
              ),
              Positioned(
                bottom: 30,
                right: 30,
                child: InkWell(
                  onTap: () {
                    print("houtui ");
                    //bottom();
                    //clearSystem();

                    Navigator.of(context).pushNamed("amap");  // addmap  amap

                  },
                  child: Container(
                    alignment: Alignment.center,
                    width: 60,
                    height: 40,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(40),
                      color: Colors.blue,
                    ),
                    child: Center(
                      child: Text(
                        "定位",
                        style: TextStyle(
                            fontSize: 14,
                            color: Colors.amberAccent,
                            fontWeight: FontWeight.w800),
                      ),
                    ),
                  ),
                ),
              ),
              Positioned(
                top: 260,
                child: InkWell(
                  onTap: () {
                    print("houtui ");
                    bottom();
                  },
                  child: Container(
                    alignment: Alignment.center,
                    width: 80,
                    height: 80,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(80),
                      color: Colors.blue,
                    ),
                    child: Center(
                      child: Text(
                        "后退",
                        style: TextStyle(
                            fontSize: 18,
                            color: Colors.amberAccent,
                            fontWeight: FontWeight.w800),
                      ),
                    ),
                  ),
                ),
              ),
              Positioned(
                left: 20,
                top: 130,
                child: InkWell(
                  onTap: () {
                    print("zuozhuan");
                    left();
                  },
                  child: Container(
                    alignment: Alignment.center,
                    width: 80,
                    height: 80,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(80),
                      color: Colors.blue,
                    ),
                    child: Center(
                      child: Text(
                        "左转",
                        style: TextStyle(
                            fontSize: 18,
                            color: Colors.amberAccent,
                            fontWeight: FontWeight.w800),
                      ),
                    ),
                  ),
                ),
              ),
              Positioned(
                right: 20,
                top: 130,
                child: InkWell(
                  onTap: () {
                    print("youzhuan");
                    right();
                  },
                  child: Container(
                    alignment: Alignment.center,
                    width: 80,
                    height: 80,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(80),
                      color: Colors.blue,
                    ),
                    child: Center(
                      child: Text(
                        "右转",
                        style: TextStyle(
                            fontSize: 18,
                            color: Colors.amberAccent,
                            fontWeight: FontWeight.w800),
                      ),
                    ),
                  ),
                ),
              ),
              Positioned(
                top: 130,
                child: InkWell(
                  onTap: () {
                    print("tingzhi");
                    centerstop();
                  },
                  child: Container(
                    alignment: Alignment.center,
                    width: 80,
                    height: 80,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(80),
                      color: Colors.blue,
                    ),
                    child: Center(
                      child: Text(
                        "停止",
                        style: TextStyle(
                            fontSize: 18,
                            color: Colors.amberAccent,
                            fontWeight: FontWeight.w800),
                      ),
                    ),
                  ),
                ),
              ),
              Positioned(
                top: 380,
                left: 50,
                child: InkWell(
                  onTap: () {
                    print("jiasu");
                    leftbottom();
                  },
                  child: Container(
                    alignment: Alignment.center,
                    width: 100,
                    height: 60,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(60),
                      color: Colors.blue,
                    ),
                    child: Center(
                      child: Text(
                        "加速",
                        style: TextStyle(
                            fontSize: 18,
                            color: Colors.amberAccent,
                            fontWeight: FontWeight.w800),
                      ),
                    ),
                  ),
                ),
              ),
              Positioned(
                top: 380,
                right: 50,
                child: InkWell(
                  onTap: () {
                    print("jiansu");
                    rightbottom();
                  },
                  child: Container(
                    alignment: Alignment.center,
                    width: 100,
                    height: 60,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(60),
                      color: Colors.blue,
                    ),
                    child: Center(
                      child: Text(
                        "减速",
                        style: TextStyle(
                            fontSize: 18,
                            color: Colors.amberAccent,
                            fontWeight: FontWeight.w800),
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
